package nit.wave.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import nit.wave.model.Biaobai;
import nit.wave.utils.JdbcUtils;

public class BiaobaiDao {

	public static List<Biaobai> findBiaobai(int type,int start,int length) throws SQLException {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<Biaobai> list = new ArrayList<Biaobai>();
		try {
			String sql = null;
			conn = JdbcUtils.getConnection();
			if (type == 0) {
				sql = "select * from nitbiaobai where id<"+start+" order by id desc limit "+length;
			} else {
				sql = "select * from nitbiaobai where type = " + type +" and id<"+start + " order by id desc limit "+length;
			}
			System.out.println(sql);
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()) {
				Biaobai biaobai = new Biaobai();
				biaobai.setAddtime(rs.getObject("addtime").toString());
				biaobai.setContent(rs.getObject("content").toString());
				biaobai.setId(rs.getInt("id"));
				biaobai.setNikeName(rs.getObject("nikeName").toString());
				biaobai.setType(rs.getInt("type"));
				biaobai.setZan(rs.getInt("zan"));
				biaobai.setRemake(rs.getObject("remake").toString());
				list.add(biaobai);
			}
		} finally {
			JdbcUtils.free(rs, ps, conn);
		}
		return list;
	}

	public static int  insertBiaobai(Biaobai biaobai) throws Exception{
		Connection conn = null;
		PreparedStatement ps = null;
		int result = 0;
		try {
			conn = JdbcUtils.getConnection();
			String sql = "insert into nitbiaobai(nikeName, content, addtime,type,zan ,remake) values (?,?,?,?,?,?)";
			ps = (PreparedStatement) conn.prepareStatement(sql);
			ps = conn.prepareStatement(sql);
			ps.setString(1, biaobai.getNikeName());
			ps.setString(2, biaobai.getContent());
			ps.setString(3, biaobai.getAddtime());
			ps.setInt(4, biaobai.getType());
			ps.setInt(5, biaobai.getZan());
			ps.setString(6, biaobai.getRemake());
			result = ps.executeUpdate();
		} finally {
			JdbcUtils.free(null, ps, conn);
		}
		return result;

	}
}
